package com.example.music.controller;

import com.example.music.model.User;
import com.example.music.service.UserService;
import com.example.music.tools.Constant;
import com.example.music.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 负责用户
 */
@RestController
/*@RequestMapping(value ="/user" )*/
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login2")
    public ResponseBodyMessage<User> login2(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {
        //
        User userLogin = new User();
        userLogin.setUsername(username);
        userLogin.setPassword(password);
        User user = userService.login(userLogin);

        //对查询到的结果，进行判断
        if (user == null) {
            //登录失败
            System.out.println("登录失败");
            //状态码为负数表示，登录失败，message是错误信息，userLogin是 按个用户登录失败了。
            return new ResponseBodyMessage<>(-1, "登录失败", userLogin);
        } else {
            //登录成功
            HttpSession session = request.getSession(true);
            userLogin.setPassword("");
            session.setAttribute(Constant.USERINFO_SESSION_KEY, user);
            userLogin.setPassword("");
            return new ResponseBodyMessage<>(0, "登录成功", userLogin);
        }
    }

    /*@Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;*/
    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @RequestMapping(value = "/login")
    public ResponseBodyMessage<User> login(@RequestParam String username,@RequestParam String password,
                                            HttpServletRequest request){
        //g根据 前段传递的 用户名 username ，来查询对应的用户信息
        User user = userService.selectByName(username);

        //对查询到的结果，进行判断
        if (user == null){
            //登录失败[用户名不存在]
            //状态码为负数表示，登录失败，message是错误信息，userLogin是 按个用户登录失败了。
            return new ResponseBodyMessage<>(-1,"登录失败",user);
        }else {
            //用户名存在
            //判断 密码 是否和前段传递的数据是一致的
            boolean flag = bCryptPasswordEncoder.matches(password,user.getPassword());
            if(flag) {
                HttpSession session =request.getSession(true);
                user.setPassword("");
                session.setAttribute(Constant.USERINFO_SESSION_KEY,user);
                return new ResponseBodyMessage<>(0,"登录成功",user);
            }
            user.setPassword("");//不返回密码,安全
            return new ResponseBodyMessage<>(-1,"登录失败",user);
        }
    }



}
